package sv_ws

import (
	"fmt"
	"venus/core"
	"venus/util/zlog"
)

// SvWs ws服务
type SvWs struct {
	BindMap map[string]func(*WsMsg) //触发列表
}

var _Sv *SvWs

// NewSv 定时服务
func NewSv(fnRegisters ...func()) *SvWs {
	_Sv = new(SvWs)
	_Sv.BindMap = make(map[string]func(*WsMsg))
	for _, fn := range fnRegisters {
		fn()
	}
	return _Sv
}

func (sv *SvWs) Init() {
	zlog.Info(sv.Name() + " Init")

	core.BindMsgExec(core.MsgTypeWsRequest, sv.Exec)
}

func (sv *SvWs) Run() {
	zlog.Info(sv.Name() + " Run")

	serveStart()
}

func (sv *SvWs) Destroy() {
	zlog.Info(sv.Name() + " Destroy")
}

func (sv *SvWs) Name() string {
	return "SvWs"
}

func (sv *SvWs) Bind(t string, fn func(*WsMsg)) {
	sv.BindMap[t] = fn
}

func (sv *SvWs) Exec(e *core.Msg) {
	msg := e.Data.(*WsMsg)
	fn, ok := sv.BindMap[msg.Msg.Cmd]
	if ok {
		fn(msg)
	} else {
		fmt.Println("无效消息：", msg.Msg.Cmd)
	}
}

func AddMsg(wsMsg *WsMsg) {
	msg := &core.Msg{
		Type: core.MsgTypeWsRequest,
		Data: wsMsg,
	}
	core.AddMsg(msg)
}
